package com.wushijia.highconcurrency.threadpool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.wushijia.highconcurrency.utils.ThreadPoolExecutorUtils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExtThreadPool {

  public static void main(String[] args) throws InterruptedException {

    ExecutorService es = new ThreadPoolExecutor(2, 5, 1L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
        new ThreadFactoryBuilder().setNameFormat("pool-%d").setUncaughtExceptionHandler((Thread t, Throwable e) -> {
          log.error("pool happen exception, thread is {}", t, e);
        }).build()) {
      @Override
      protected void beforeExecute(Thread thread, Runnable runnable) {
        System.out.println("准备执行：" + ((MyTask) runnable).name);
      }

      @Override
      protected void afterExecute(Runnable runnable, Throwable throwable) {
        System.out.println("执行完成：" + ((MyTask) runnable).name);
      }

      @Override
      protected void terminated() {
        System.out.println("线程池退出");
      }
    };
    for (int i = 0; i < 15; i++) {
      MyTask task = new MyTask("task " + i);
      es.execute(task);
      Thread.sleep(10);
      log.info(ThreadPoolExecutorUtils.getThreadPoolExecutorInfo("MyTask", (ThreadPoolExecutor) es));
    }
//    es.shutdown();
  }

  public static class MyTask implements Runnable {

    String name;

    public MyTask(String name) {
      this.name = name;
    }

    @Override
    public void run() {
      System.out.println("正在执行:Thread ID: " + Thread.currentThread().getName() + ":Task Name=" + this.name);
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
